<template>
  <div class="review-container">
        <!-- 顶部返回导航栏 -->
    <el-page-header @back="goBack" title="返回订单列表">
      <template #content>
        <span class="page-header-title">订单评价</span>
      </template>
    </el-page-header>

    <!-- 评价内容卡片 -->
    <el-card class="review-card">
      <!-- 订单基本信息区域 -->
      <div class="order-info">
        <!-- 商品图片 -->
        <el-image 
          class="product-image" 
          :src="order.product_image" 
          fit="cover"
        >
          <!-- 图片加载失败时的占位符 -->
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <!-- 商品和订单信息 -->
        <div class="product-info">
          <h3>{{ order.product_name || '商品已下架' }}</h3>
          <p>订单号: {{ order.order_code }}</p>
          <p>下单时间: {{ formatTime(order.create_time) }}</p>
        </div>
      </div>

      <el-divider />

      <!-- 评价表单 -->
      <el-form 
        ref="reviewFormRef" 
        :model="reviewForm" 
        :rules="rules" 
        label-position="top"
        class="review-form"
      >
        <!-- 评分组件 -->
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="reviewForm.rating"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            show-text
            :texts="['很差', '较差', '一般', '不错', '很棒']"
          />
        </el-form-item>

        <!-- 评价内容文本框 -->
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            :rows="5"
            placeholder="请写下您的使用感受，对其他买家会有很大帮助"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 图片上传组件（预留功能） -->
        <el-form-item label="上传图片（可选）">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="3"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传3张图片（当前仅支持文字评价）</div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitReview"
            :loading="submitting"
          >
            提交评价
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture, Plus } from '@element-plus/icons-vue'
import apiClient from '../../utils/request'
import { DEFAULT_IMAGE } from '../../utils/orderUtils'

// 路由实例
const route = useRoute()
const router = useRouter()

// 订单信息响应式对象
const order = ref({
  order_code: '',
  product_name: '',
  product_image: '',
  create_time: ''
})

// 评价表单数据
const reviewForm = ref({
  rating: 5,  // 默认5星
  content: ''
})

// 图片上传列表
const fileList = ref([])
// 提交状态标志
const submitting = ref(false)

// 表单验证规则
const rules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取订单信息的方法
const fetchOrder = async () => {
  try {
    const token = localStorage.getItem('access_token')
    const response = await apiClient.get(`/api/orders/${route.params.order_code}/`, )
    order.value = response.data
    
    // 获取商品信息
    try {
      const productResponse = await apiClient.get(`/api/products/buyer/${response.data.product_code}/`)
      order.value.product_name = productResponse.data.name
      order.value.product_image = productResponse.data.images?.[0]?.url || DEFAULT_IMAGE
    } catch (error) {
      console.error('获取商品信息失败:', error)
      order.value.product_name = '商品已下架'
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单信息失败')
    router.push('/orders')
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 处理图片上传
const handleImageChange = (file) => {
  fileList.value.push(file)
}

// 处理图片移除
const handleRemove = (file) => {
  const index = fileList.value.findIndex(f => f.uid === file.uid)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
}

// 提交评价
const submitReview = async () => {
  try {
    submitting.value = true
    
    const payload = {
      order: order.value.id,
      content: reviewForm.value.content,
      rating: reviewForm.value.rating
    }

    await apiClient.post('/api/orders/reviews/', payload,)

    ElMessage.success('评价提交成功！')
    router.push('/orders')
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error(error.response?.data?.message || '评价提交失败')
  } finally {
    submitting.value = false
  }
}

// 返回订单列表
const goBack = () => {
  router.push('/orders')
}

onMounted(() => {
  fetchOrder()
})
</script>

<style scoped>
.review-container {
  padding: 20px;
  max-width: 1200px;
  margin: 100px;
}

.page-header-title {
  font-size: 18px;
  font-weight: 500;
}

.review-card {
  margin-top: 20px;
  width: 100%;
  margin-left: auto;  /* 水平居中 */
  margin-right: auto;
}

.order-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.product-info {
  flex: 1;
}

.product-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.product-info p {
  margin: 5px 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.review-form {
  margin-top: 20px;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>